<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../rest.css">
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
<script>

    class DragEle {
        posX = null
        posY = null
        constructor(ele) {
            this.target = ele
            this.dragStart()
        }
        dragStart() {
            this.dragDown()
        }
        dragEnd() {
            this.target.onmousedown = null
        }
        dragDown() {
            this.target.onmousedown = function (e) {
                var e = e || window.event
                this.posX = e.offsetX
                this.posY = e.offsetY
                this.dragMove()
                this.dragUp()
                console.log('onmousedown', this)
            }.bind(this)
        }
        dragMove() {
            document.onmousemove = (e) => { //this => 依赖父作用域this指向(dragEle)
                var e = e || window.event
                var x = e.pageX - this.posX
                var y = e.pageY - this.posY
                this.target.style.left = x + "px"
                this.target.style.top = y + "px"
                console.log('onmousemove', this)
            }
        }
        dragUp() {
            // this -> 调用此方法的实例化对象
            document.onmouseup = function () {
                document.onmousemove = null
                document.onmouseup = null
                console.log('onmouseup', this)
            }
        }
    }
    var boxList = document.getElementsByClassName("box")
    for (var i = 0; i < boxList.length; i++) {
        var box = boxList[i]
        var obj = new DragEle(box)
    }
</script>

</html>